package top.myhdg.bijou;

import android.Manifest;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.Dialog;
import android.app.DownloadManager;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.print.PrintAttributes;
import android.print.PrintDocumentAdapter;
import android.print.PrintManager;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Base64;
import android.util.DisplayMetrics;
import android.util.Patterns;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.webkit.CookieManager;
import android.webkit.DownloadListener;
import android.webkit.GeolocationPermissions;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.hitomi.cslibrary.CrazyShadow;
import com.hitomi.cslibrary.base.CrazyShadowDirection;
import com.kymjs.rxvolley.RxVolley;
import com.kymjs.rxvolley.client.HttpCallback;
import com.qmuiteam.qmui.widget.dialog.QMUIDialog;
import com.qmuiteam.qmui.widget.dialog.QMUIDialogAction;
import com.qmuiteam.qmui.widget.dialog.QMUITipDialog;
import com.qmuiteam.qmui.widget.popup.QMUIListPopup;
import com.qmuiteam.qmui.widget.popup.QMUIPopup;
import com.youngfeng.snake.Snake;

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Objects;

import top.myhdg.bijou.activity.BaseActivity;
import top.myhdg.bijou.activity.BookmarkActivity;
import top.myhdg.bijou.activity.HistoryActivity;
import top.myhdg.bijou.activity.SettingsActivity;
import top.myhdg.bijou.activity.ShowImgActivity;
import top.myhdg.bijou.activity.SourceActivity;
import top.myhdg.bijou.colorUi.util.ColorUiUtil;
import top.myhdg.bijou.colorUi.util.SharedPreferencesMgr;
import top.myhdg.bijou.part.EnhanceWebView;
import top.myhdg.bijou.qrcodelib.CaptureActivity;
import top.myhdg.bijou.sqlite.History;
import top.myhdg.bijou.sqlite.HistoryDao;
import top.myhdg.bijou.utils.MyHdgUtils;

import static com.qmuiteam.qmui.util.QMUIDisplayHelper.dp2px;

public class MainActivity extends BaseActivity {
    //==========主页控件==========
    ImageButton buttonSearch;//查找按钮
    ImageButton buttonQR;//二维码按钮
    ImageButton buttonGo;//转到按钮
    ImageButton buttonRefresh;//刷新按钮
    ImageButton buttonStop;//停止加载按钮
    ImageButton buttonBackOff;//后退按钮
    ImageButton buttonForward;//前进按钮
    ImageButton buttonHome;//主页按钮
    ImageButton buttonMulti;//多窗口按钮
    ImageButton buttonMore;//选项按钮
    ImageButton buttonCloseSearch;//关闭查找按钮
    ImageButton buttonNext;//查找下一项按钮

    EditText editWebsite;//地址栏
    TextView startSearch;//主页搜索栏
    TextView oneText;//一言
    EditText editSearch;//查找栏

    ImageView bijouImg;//BIJOU图标

    ArrayList<EnhanceWebView> webViews;//网页控件

    //==========全屏播放视频==========
    FrameLayout layoutFullVideo;//全屏播放视频布局
    WebChromeClient.CustomViewCallback mCallback;
    //==========全屏播放视频==========

    LinearLayout layoutFind;//查找布局
    LinearLayout layoutWebView;//网页控件布局
    LinearLayout layoutTopBar;//顶栏布局
    LinearLayout layoutBottomBar;//底栏布局
    ImageButton buttonExitFull;//退出全屏按钮

    LinearLayout layoutHome;//主页布局
    FrameLayout layoutPage;//网页布局

    ListView suggestListView;//搜索提示列表
    //==========主页控件==========

    ArrayList<String> suggestList;//搜索提示列表数据
    ArrayAdapter<String> adapter;//搜索列表适配器

    //==========配置文件相关==========
    SharedPreferences configure;//设置配置文件
    SharedPreferences recoveryConfigure;//恢复页配置文件
    SharedPreferences noImgConfigure;//无图模式配置文件
    SharedPreferences fullConfigure;//全屏模式配置文件
    SharedPreferences historyConfigure;//是否记录历史配置文件
    SharedPreferences.Editor editorR;//恢复页配置修改器
    SharedPreferences.Editor editorM;//无图模式配置修改器
    SharedPreferences.Editor editorF;//全屏模式配置修改器
    SharedPreferences.Editor editorH;//是否记录历史配置修改器
    //==========配置文件相关==========

    ClipboardManager clipboardManager;//剪贴板

    CookieManager cookieManager;//Cookies管理器

    QMUIListPopup longClickImgPopup;//长按图片窗口
    QMUIListPopup longClickAncPopup;//长按链接窗口

    HistoryDao historyDao;//历史记录

    long firstTime = 0;//第一次按下返回键时间

    boolean paste = false;//是否需要粘贴

    boolean isLoading = false;//是否正在加载

    boolean onHistory = true;//是否记录历史

    String customUA = "";//自定义UA

    private String longClickUrl = "";// 长按目标链接

    int frontPage = 0;//显示在前端的页面

    //==========读取配置文件==========
    String recoveryP;//恢复页
    int recoveryNum;//恢复页数量
    String engine;//搜索引擎
    String topContent;//地址栏内容
    boolean isPaste;//是否粘贴
    boolean clearCache;//退出时清除Cache
    boolean clearFormData;//退出时清除表单数据
    boolean clearHistory;//退出时清除历史记录
    boolean clearStorage;//退出时清除网页存储
    boolean clearCookies;//退出时清除Cookies
    boolean dropDown;//下拉刷新
    boolean slideHori;//滑前进后退
    boolean slideVert;//上下滑动控制顶栏底栏
    boolean volKey;//音量键翻页
    boolean geo;//允许定位
    boolean intercept;//拦截广告
    boolean javascript;//启用JavaScript
    boolean isRecovery;//是否需要加载恢复页
    boolean recovery;//是否恢复
    boolean noImg;//无图模式
    boolean full;//全屏模式
    //==========读取配置文件==========

    String externalUrl;//接受外部地址

    //==========滑动前进后退==========
    int startX;//开始按下时X位置
    int startY;//开始按下时Y位置
    //==========滑动前进后退==========

    //==========文件上传相关==========
    ValueCallback<Uri> uploadMessage;
    ValueCallback<Uri[]> uploadMessageAboveL;
    final static int FILE_CHOOSER_RESULT_CODE = 10000;//文件上传请求码
    //==========文件上传相关==========

    public static String html;//网页源码

    final static int SETTING = 1;
    final static int BOOKMARK = 2;
    final static int HISTORY = 3;
    final static int QR = 4;
    final static int UPDATE = 5;
    final static int QQ = 6;

    MoreDialog moreDialog;
    ToolDialog toolDialog;

    ArrayList<PageItem> pages;
    PageAdapter pageAdapter;
    MultiDialog multiDialog;

    String nightCode;//夜间模式CSS

    //===这两个没什么用处(治强迫症)===
    int r0;
    boolean r1;
    //===这两个没什么用处(治强迫症)===

    @SuppressLint({"SetJavaScriptEnabled", "ClickableViewAccessibility"})
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Snake.enableDragToClose(this, false);//关闭滑动返回
        WebView.enableSlowWholeDocumentDraw();
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);//设置不被输入法顶起
        setContentView(R.layout.activity_main);

        //==========检查权限==========
        checkPermissions(new String[]{Manifest.permission.INTERNET,
                Manifest.permission.CHANGE_NETWORK_STATE,
                Manifest.permission.READ_EXTERNAL_STORAGE,
                Manifest.permission.WRITE_EXTERNAL_STORAGE});
        //==========检查权限==========

        //==========读取配置文件==========
        configure = getSharedPreferences("BijouConfigure", MODE_PRIVATE);
        engine = configure.getString("Engine", "http://www.baidu.com/s?wd=");
        topContent = configure.getString("TopContent", "title");
        isPaste = configure.getBoolean("Paste", false);
        dropDown = configure.getBoolean("Dropdown", false);
        slideHori = configure.getBoolean("SlideHori", false);
        slideVert = configure.getBoolean("SlideVert", false);
        volKey = configure.getBoolean("VolKey", false);
        geo = configure.getBoolean("Geo", true);
        intercept = configure.getBoolean("Intercept", true);
        javascript = configure.getBoolean("JavaScript", true);
        recovery = configure.getBoolean("Recovery", false);

        noImgConfigure = getPreferences(MODE_PRIVATE);
        noImg = noImgConfigure.getBoolean("NoImg", false);

        fullConfigure = getPreferences(MODE_PRIVATE);
        full = fullConfigure.getBoolean("Full", false);

        historyConfigure = getPreferences(MODE_PRIVATE);
        onHistory = historyConfigure.getBoolean("OnHistory", true);
        //==========读取配置文件==========

        clipboardManager = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);//获取剪贴板

        historyDao = new HistoryDao(MainActivity.this);

        findViews();//获取控件

        //读取夜间模式CSS
        InputStream inputStream = MainActivity.this.getResources().openRawResource(R.raw.night);
        byte[] buffer = new byte[0];
        try {
            buffer = new byte[inputStream.available()];
            r0 = inputStream.read(buffer);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                inputStream.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        nightCode = Base64.encodeToString(buffer, Base64.NO_WRAP);

        //==========读取恢复网页==========
        recoveryConfigure = getPreferences(MODE_PRIVATE);
        isRecovery = true;
        if (recovery) {
            recoveryNum = recoveryConfigure.getInt("RecoveryNum", 1);
        }
        //==========读取恢复网页==========

        cookieManager = CookieManager.getInstance();

        //==========添加WebView==========
        webViews = new ArrayList<>();

        if (recovery) {
            for (int i = 0; i < recoveryNum; i++) {
                String recoveryPage = "RecoveryPage" + i;
                recoveryP = recoveryConfigure.getString(recoveryPage, "about:blank");

                addNewPage(seniorUrl(recoveryP));
            }
            isRecovery = false;
        } else {
            addNewPage("about:blank");
        }
        //==========添加WebView==========

        setListeners();//设置监听器

        //==========接受外部调起相关==========
        Intent intent = getIntent();
        try {
            if (Objects.equals(intent.getScheme(), "file")) {
                externalUrl = "file:" + Objects.requireNonNull(intent.getData()).getPath();
                addNewPage(externalUrl);
            } else {
                externalUrl = intent.getDataString();
                if (externalUrl != null) {
                    addNewPage(seniorUrl(externalUrl));
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        //==========接受外部调起相关==========
    }

    private void findViews() {
        layoutFind = findViewById(R.id.layoutFind);
        layoutTopBar = findViewById(R.id.layoutTopBar);
        layoutBottomBar = findViewById(R.id.layoutBottomBar);
        buttonExitFull = findViewById(R.id.buttonExitFull);
        layoutFullVideo = findViewById(R.id.layoutFullVideo);
        editWebsite = findViewById(R.id.editWebsite);
        startSearch = findViewById(R.id.startSearch);
        oneText = findViewById(R.id.oneText);
        layoutWebView = findViewById(R.id.layoutWebView);
        suggestListView = findViewById(R.id.suggestList);
        layoutHome = findViewById(R.id.layoutHome);
        layoutPage = findViewById(R.id.layoutPage);
        buttonSearch = findViewById(R.id.buttonSearch);
        buttonQR = findViewById(R.id.buttonQR);
        buttonGo = findViewById(R.id.buttonGo);
        buttonRefresh = findViewById(R.id.buttonRefresh);
        buttonStop = findViewById(R.id.buttonStop);
        buttonBackOff = findViewById(R.id.buttonBackOff);
        buttonForward = findViewById(R.id.buttonForward);
        buttonHome = findViewById(R.id.buttonHome);
        buttonMulti = findViewById(R.id.buttonMulti);
        buttonMore = findViewById(R.id.buttonMore);
        editSearch = findViewById(R.id.editSearch);
        buttonCloseSearch = findViewById(R.id.buttonCloseSearch);
        buttonNext = findViewById(R.id.buttonNext);
        bijouImg = findViewById(R.id.bijouImg);
    }

    private void setListeners() {

        moreDialog = new MoreDialog(MainActivity.this, R.style.dialogTheme);
        toolDialog = new ToolDialog(MainActivity.this, R.style.dialogTheme);
        multiDialog = new MultiDialog(MainActivity.this, R.style.dialogTheme);

        //开关一次，防止空数据
        multiDialog.show();
        multiDialog.dismiss();
        //开关一次，加快下次启动速度
        moreDialog.show();
        moreDialog.dismiss();
        toolDialog.show();
        toolDialog.dismiss();

        if (full) {
            fullScreen();
        }

        buttonExitFull.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showTipDialog(0, "全屏模式已关闭", 900);
                full = false;
                editorF = fullConfigure.edit();
                editorF.putBoolean("Full", full);
                editorF.apply();

                exitFullScreen();
            }
        });

        bijouImg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (layoutBottomBar.getVisibility() == View.GONE) {
                    layoutBottomBar.setVisibility(View.VISIBLE);
                    if (isLand()) {
                        LinearLayout topBottomLayout = findViewById(R.id.topBottomLayout);
                        topBottomLayout.setVisibility(View.VISIBLE);
                        layoutTopBar.setVisibility(View.VISIBLE);
                    }
                } else {
                    layoutBottomBar.setVisibility(View.GONE);
                    if (isLand()) {
                        LinearLayout topBottomLayout = findViewById(R.id.topBottomLayout);
                        topBottomLayout.setVisibility(View.GONE);
                        layoutTopBar.setVisibility(View.GONE);
                    }
                }
            }
        });

        editWebsite.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_ENTER) {
                    String string = editWebsite.getText().toString();
                    if (string.length() > 0) {
                        webViews.get(frontPage).getWebView().loadUrl(seniorUrl(string));
                        openPage();
                    } else {
                        openHome();
                    }

                    MyHdgUtils.closeKeyboard(MainActivity.this, editWebsite);
                    editWebsite.setText("");
                    editWebsite.clearFocus();
                    return true;
                }
                return false;
            }
        });

        editWebsite.setSelectAllOnFocus(true);
        editWebsite.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    buttonGo.setVisibility(View.VISIBLE);//显示转到按钮
                    buttonQR.setVisibility(View.GONE);//隐藏二维码按钮
                    buttonRefresh.setVisibility(View.GONE);//隐藏刷新按钮
                    editWebsite.setText(webViews.get(frontPage).getWebView().getUrl());
                    editWebsite.selectAll();

                    if (editWebsite.getText().toString().equals("about:blank")) {
                        editWebsite.setText("");
                        editWebsite.setHint("搜你所想");
                    }

                    openSuggestList();

                    if (paste) {//取得复制数据
                        if (clipboardManager.hasPrimaryClip()) {
                            ClipData clipData = clipboardManager.getPrimaryClip();
                            ClipData.Item item = clipData.getItemAt(0);
                            editWebsite.setText(item.getText().toString());
                            editWebsite.selectAll();
                        }
                        paste = false;
                    }
                } else {
                    buttonGo.setVisibility(View.GONE);
                    buttonQR.setVisibility(View.VISIBLE);
                    buttonRefresh.setVisibility(View.VISIBLE);
                    editWebsite.setText("");
                    setTopHint();
                    MyHdgUtils.closeKeyboard(MainActivity.this, editWebsite);
                }
            }
        });

        suggestList = new ArrayList<>();
        adapter = new ArrayAdapter<>(MainActivity.this, R.layout.simple_list_item_1, suggestList);
        suggestListView.setAdapter(adapter);

        suggestListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                editWebsite.setText(suggestList.get(i));
                editWebsite.setSelection(editWebsite.getText().toString().length());
            }
        });

        editWebsite.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                String string = editWebsite.getText().toString();
                if (string.equals("about:blank")) {
                    string = "";
                }
                getSuggestList(string);
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });

        new CrazyShadow.Builder()
                .setContext(MainActivity.this)
                .setDirection(CrazyShadowDirection.ALL)
                .setShadowRadius(dp2px(MainActivity.this, 5))
                .setCorner(dp2px(MainActivity.this, 16))
                .setBackground(SharedPreferencesMgr.getInt("Theme", 0) == 0 ? Color.parseColor("#FFFFFF") : Color.parseColor("#404040"))
                .setImpl(CrazyShadow.IMPL_DRAW)
                .action(startSearch);
        startSearch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                editWebsite.requestFocus();
                MyHdgUtils.openKeyboard(MainActivity.this, editWebsite);
            }
        });

        buttonSearch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (layoutPage.getVisibility() == View.VISIBLE) {
                    if (layoutFind.getVisibility() == View.GONE) {
                        layoutFind.setVisibility(View.VISIBLE);
                        editSearch.requestFocus();
                        MyHdgUtils.openKeyboard(MainActivity.this, editSearch);
                    } else {
                        layoutFind.setVisibility(View.GONE);
                        editSearch.setText("");
                        editSearch.clearFocus();
                        webViews.get(frontPage).getWebView().clearMatches();//清除高亮状态
                        MyHdgUtils.closeKeyboard(MainActivity.this, editSearch);
                    }
                }
            }
        });

        buttonQR.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this, CaptureActivity.class);
                startActivityForResult(intent, QR);
            }
        });

        buttonGo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String string = editWebsite.getText().toString();
                if (string.length() > 0) {
                    webViews.get(frontPage).getWebView().loadUrl(seniorUrl(string));
                    openPage();
                } else {
                    openHome();
                }
            }
        });

        buttonRefresh.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                webViews.get(frontPage).getWebView().reload();
            }
        });

        buttonStop.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                webViews.get(frontPage).getWebView().stopLoading();
            }
        });

        setCtrlWebBtn();
        buttonBackOff.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                goBack();
            }
        });
        buttonForward.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                goForward();
            }
        });

        //==========主页键点击和长按==========
        buttonHome.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                webViews.get(frontPage).getWebView().stopLoading();
                webViews.get(frontPage).getWebView().loadUrl("about:blank");//加载主页
                openHome();
            }
        });
        buttonHome.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {//长按转到地址栏
                if (editWebsite.hasFocus()) {
                    MyHdgUtils.closeKeyboard(MainActivity.this, editWebsite);
                    if (webViews.get(frontPage).getWebView().getUrl().equals("about:blank")) {
                        openHome();
                    } else {
                        openPage();
                    }
                } else {
                    MyHdgUtils.openKeyboard(MainActivity.this, editWebsite);
                    openSuggestList();
                }
                return true;
            }
        });
        //==========主页键点击和长按==========

        //==========多窗口相关==========
        buttonMulti.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                pages = new ArrayList<>();
                for (EnhanceWebView anEnhanceWebView : webViews) {
                    final int pageId = webViews.indexOf(anEnhanceWebView);
                    String pageTitle = anEnhanceWebView.getWebView().getTitle();
                    String pageSite = anEnhanceWebView.getWebView().getUrl();
                    pages.add(new PageItem(pageId, pageTitle, pageSite, new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            if (webViews.size() == 1) {//若删除时只剩一页，则需要新生成一页
                                EnhanceWebView webViewD = webViews.get(frontPage);
                                destroyWebView(webViewD);
                                webViews.clear();
                                pages.clear();
                                pageAdapter.notifyDataSetChanged();

                                addNewPage("about:blank");
                            } else {
                                EnhanceWebView webViewD = webViews.get(pageId);
                                destroyWebView(webViewD);
                                pages.remove(pageId);
                                webViews.remove(webViewD);
                                pageAdapter.notifyDataSetChanged();
                                if (frontPage >= 1) {
                                    webViews.get(--frontPage).setVisibility(View.VISIBLE);
                                } else {
                                    webViews.get(0).setVisibility(View.VISIBLE);
                                }
                                setTopHint();

                                if (webViews.get(frontPage).getWebView().getUrl().equals("about:blank")) {
                                    openHome();
                                } else {
                                    openPage();
                                }
                            }
                            multiDialog.dismiss();

                            setCtrlWebBtn();
                        }
                    }));
                }
                pageAdapter = new PageAdapter(MainActivity.this, R.layout.item_mutli, pages);
                try {
                    multiDialog.setPageAdapter(pageAdapter);
                } catch (Exception e) {
                    e.printStackTrace();
                }

                multiDialog.show();

                multiDialog.setPageListItemListener(new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                        multiDialog.dismiss();

                        webViews.get(frontPage).setVisibility(View.GONE);//隐藏之前显示页面
                        frontPage = position;
                        webViews.get(frontPage).setVisibility(View.VISIBLE);//显示点击的页面
                        setTopHint();

                        if (webViews.get(frontPage).getWebView().getUrl().equals("about:blank")) {
                            openHome();
                        } else {
                            openPage();
                        }

                        setCtrlWebBtn();
                    }
                });

                multiDialog.setAddPageClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        multiDialog.dismiss();

                        addNewPage("about:blank");
                    }
                });

                multiDialog.setIncognitoClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        multiDialog.dismiss();

                        onHistory = !onHistory;
                        editorH = historyConfigure.edit();
                        editorH.putBoolean("OnHistory", onHistory);
                        editorH.apply();
                        if (onHistory) {
                            showTipDialog(0, "无痕浏览已关闭", 900);
                        } else {
                            showTipDialog(0, "无痕浏览已开启", 900);
                        }
                    }
                });

                multiDialog.setEmptyClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        multiDialog.dismiss();

                        new QMUIDialog.MessageDialogBuilder(MainActivity.this)
                                .setTitle("请确认")
                                .setMessage("关闭所有窗口？")
                                .addAction("取消", new QMUIDialogAction.ActionListener() {
                                    @Override
                                    public void onClick(QMUIDialog dialog, int index) {
                                        dialog.dismiss();
                                    }
                                })
                                .addAction(0, "关闭", QMUIDialogAction.ACTION_PROP_NEGATIVE, new QMUIDialogAction.ActionListener() {
                                    @Override
                                    public void onClick(QMUIDialog dialog, int index) {
                                        for (EnhanceWebView anEnhanceWebView : webViews) {
                                            destroyWebView(anEnhanceWebView);
                                        }
                                        webViews.clear();

                                        addNewPage("about:blank");

                                        dialog.dismiss();
                                    }
                                })
                                .create().show();
                    }
                });
            }
        });

        buttonMulti.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                addNewPage("about:blank");
                return true;
            }
        });
        //==========多窗口相关==========

        //==========选项菜单==========
        buttonMore.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                moreDialog.show();
            }
        });
        //==========选项菜单==========

        //==========长按选项按钮==========
        buttonMore.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {//长按选项打开/关闭查找框
                if (layoutPage.getVisibility() == View.VISIBLE) {
                    if (layoutFind.getVisibility() == View.VISIBLE) {
                        layoutFind.setVisibility(View.GONE);
                        editSearch.setText("");
                        editSearch.clearFocus();
                        webViews.get(frontPage).getWebView().clearMatches();
                        MyHdgUtils.closeKeyboard(MainActivity.this, editSearch);
                    } else {
                        layoutFind.setVisibility(View.VISIBLE);
                        editSearch.requestFocus();
                        MyHdgUtils.openKeyboard(MainActivity.this, editSearch);
                    }
                }
                return true;
            }
        });
        //==========长按选项按钮==========


        //==========查找内容栏逻辑==========
        editSearch.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                webViews.get(frontPage).getWebView().findAllAsync(s.toString());
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        buttonCloseSearch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                layoutFind.setVisibility(View.GONE);
                editSearch.setText("");
                editSearch.clearFocus();
                webViews.get(frontPage).getWebView().clearMatches();
                MyHdgUtils.closeKeyboard(MainActivity.this, editSearch);
            }
        });

        buttonNext.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                webViews.get(frontPage).getWebView().findNext(true);//查找下一个
            }
        });
        //==========查找内容栏逻辑==========

        getOneText();

        oneText.setOnClickListener(new View.OnClickListener() {//单击变换一言
            @Override
            public void onClick(View view) {
                getOneText();
            }
        });

        oneText.setOnLongClickListener(new View.OnLongClickListener() {//长按复制一言
            @Override
            public boolean onLongClick(View view) {
                clipboardManager.setPrimaryClip(ClipData.newPlainText("text", oneText.getText()));
                showTipDialog(0, "一言已复制", 900);
                return true;
            }
        });
    }

    @SuppressLint("ClickableViewAccessibility")
    void initWebView(final EnhanceWebView webView, String url) {
        //==========WebView相关设置项==========
        webView.setEnabled(dropDown);//设置下拉刷新
        webView.dropDown = dropDown;
        cookieManager.acceptThirdPartyCookies(webView.getWebView());//开启第三方Cookies
        WebSettings webSettings = webView.getWebView().getSettings();
        webSettings.setJavaScriptEnabled(javascript);//设置支持Javascript
        webSettings.setLoadsImagesAutomatically(!noImg);//设置自动加载图片
        webSettings.setSupportMultipleWindows(true);//多窗口支持
        //=====向WebView暴露本地接口=====
        webView.getWebView().addJavascriptInterface(new JavascriptInterface(), "onClick");
        webView.getWebView().addJavascriptInterface(new JavascriptInterface(), "local_obj");
        //=====向WebView暴露本地接口=====
        webView.getWebView().setWebViewClient(new EnhanceWebView.BaseWebViewClient() {
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                if (!url.startsWith("http")) {//处理其他请求
                    try {
                        Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
                        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP);
                        startActivity(intent);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    return true;
                }
                return false;
            }

            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                super.onPageStarted(view, url, favicon);

                //==========屏蔽广告(注入JS)==========
                if (intercept) {
                    @SuppressLint("HandlerLeak") final Handler handler = new Handler() {
                        @Override
                        public void handleMessage(Message msg) {
                            webView.getWebView().loadUrl(getClearAdDivJs());
                        }
                    };

                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            handler.sendEmptyMessage(0x001);
                        }
                    }).start();
                }
                //==========屏蔽广告(注入JS)==========

                //注入夜间模式CSS
                if (SharedPreferencesMgr.getInt("Theme", 0) == 1) {
                    webView.getWebView().loadUrl("javascript:(function() {"
                            + "var parent = document.getElementsByTagName('head').item(0);"
                            + "var style = document.createElement('style');"
                            + "style.type = 'text/css';"
                            + "style.innerHTML = window.atob('"
                            + nightCode + "');"
                            + "parent.appendChild(style)"
                            + "})();");
                }

            }

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);

                //=====写入历史记录=====
                if (onHistory) {
                    String historyUrl = webView.getWebView().getUrl();
                    try {
                        if (!historyUrl.equals("about:blank")) {
                            @SuppressLint("SimpleDateFormat") SimpleDateFormat sDateFormat = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss");
                            String time = sDateFormat.format(new Date());
                            History history = new History(webView.getWebView().getTitle(), historyUrl, time);
                            historyDao.insertDate(history);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                }

                if (SharedPreferencesMgr.getInt("Theme", 0) == 1) {
                    webView.getWebView().loadUrl("javascript:(function() {"
                            + "var parent = document.getElementsByTagName('head').item(0);"
                            + "var style = document.createElement('style');"
                            + "style.type = 'text/css';"
                            + "style.innerHTML = window.atob('"
                            + nightCode + "');"
                            + "parent.appendChild(style)"
                            + "})();");
                }

                view.loadUrl(TagUtils.getJs(url));//全屏播放视频
                view.loadUrl("javascript:window.local_obj.showSource('<head>'+" +
                        "document.getElementsByTagName('html')[0].innerHTML+'</head>');");//获取html源码
            }
        });
        webView.getWebView().requestFocusFromTouch();//支持获取手势焦点
        webView.getWebView().setDrawingCacheEnabled(true);//开启绘制缓存
        //==========WebView相关设置项==========

        //==========添加下载监听==========
        webView.getWebView().setDownloadListener(new DownloadListener() {
            @Override
            public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) {
                Uri uri = Uri.parse(url);
                Intent intent = new Intent(Intent.ACTION_VIEW, uri);
                startActivity(intent);
            }
        });
        //==========添加下载监听==========

        //==========添加长按监听==========
        webView.getWebView().setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                WebView.HitTestResult result = ((WebView) v).getHitTestResult();
                if (result == null) {
                    return false;
                }
                int type = result.getType();
                if (type == WebView.HitTestResult.UNKNOWN_TYPE) {
                    return false;
                }
                if (type == WebView.HitTestResult.EDIT_TEXT_TYPE) {
                    return false;
                }

                switch (type) {
                    case WebView.HitTestResult.SRC_ANCHOR_TYPE: // 超链接
                        longClickUrl = result.getExtra();
                        initAnchorListPopupIfNeed();
                        longClickAncPopup.setAnimStyle(QMUIPopup.ANIM_GROW_FROM_CENTER);
                        longClickAncPopup.setPreferredDirection(QMUIPopup.DIRECTION_BOTTOM);
                        longClickAncPopup.show(v);
                        break;
                    case WebView.HitTestResult.IMAGE_TYPE: // 图片
                        longClickUrl = result.getExtra();
                        initImageListPopupIfNeed();
                        longClickImgPopup.setAnimStyle(QMUIPopup.ANIM_GROW_FROM_CENTER);
                        longClickImgPopup.setPreferredDirection(QMUIPopup.DIRECTION_BOTTOM);
                        longClickImgPopup.show(v);
                        break;
                    default:
                }
                return true;
            }
        });
        //==========添加长按监听==========

        webView.getWebView().setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {

                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        startX = (int) event.getX();
                        startY = (int) event.getY();
                        break;
                    case MotionEvent.ACTION_UP:
                        DisplayMetrics displayMetrics = new DisplayMetrics();
                        getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
                        int wide = displayMetrics.widthPixels;
                        int height = displayMetrics.heightPixels;
                        //==========左右滑动前进后退==========
                        if (slideHori) {
                            int endX = (int) event.getX();
                            if (startX < wide / 10 || startX > wide / 10 * 9) {
                                if (endX > startX && webView.getWebView().canGoBack() && endX - startX > wide / 5) {
                                    goBack();
                                } else if (endX < startX && webView.getWebView().canGoForward() && startX - endX > wide / 5) {
                                    goForward();
                                }
                            }
                        }
                        //==========左右滑动前进后退==========

                        //==========上下滑动隐藏/显示 顶栏/底栏==========
                        if (slideVert) {
                            int length;
                            if (height > wide) {
                                length = height / 3;
                            } else {
                                length = height / 2;
                            }
                            int endY = (int) event.getY();
                            if (endY > startY && endY - startY > length) {
                                exitFullScreen();
                            } else if (endY < startY && startY - endY > length) {
                                fullScreen();
                            }
                        }
                        //==========上下滑动隐藏/显示 顶栏/底栏==========

                        break;
                }

                return false;
            }
        });
        //==========滑动前进后退==========

        webView.getWebView().setWebChromeClient(new EnhanceWebView.BaseWebChromeClient() {
            //==========多窗口支持==========
            @Override
            public boolean onCreateWindow(WebView view, boolean isDialog, boolean isUserGesture, Message resultMsg) {
                if (!isDialog) {
                    WebView.HitTestResult result = view.getHitTestResult();//获取点击对象
                    addNewPage(result.getExtra());
                    openPage();
//                    WebView.WebViewTransport transport = (WebView.WebViewTransport) resultMsg.obj;
//                    transport.setWebView(webViews.get(frontPage).getWebView());
//                    resultMsg.sendToTarget();
                }
                return false;
            }

            @Override
            public void onCloseWindow(WebView window) {
                EnhanceWebView webViewD = webViews.get(frontPage);
                if (webViews.size() == 1) {//若关闭时只剩一页，则需要新生成一页
                    destroyWebView(webViewD);
                    webViews.clear();
                    addNewPage("about:blank");
                } else {
                    destroyWebView(webViewD);
                    webViews.remove(webViewD);
                    if (frontPage >= 1) {
                        webViews.get(--frontPage).setVisibility(View.VISIBLE);
                    } else {
                        webViews.get(0).setVisibility(View.VISIBLE);
                    }
                    setTopHint();
                }
                if (webViews.get(frontPage).getWebView().getUrl().equals("about:blank")) {
                    openHome();
                } else {
                    openPage();
                }
            }
            //==========多窗口支持==========

            @Override
            public void onReceivedTitle(WebView view, String title) {//设置显示网页标题
                setTopHint();
            }

            @Override
            public void onProgressChanged(WebView view, int newProgress) {//更新显示进度条
                try {
                    if (webViews.get(frontPage).getWebView() == view) {
                        if (view.getUrl().equals("about:blank")) {
                            openHome();
                        } else {
                            openPage();
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }

                if (SharedPreferencesMgr.getInt("Theme", 0) == 1) {
                    webView.getWebView().loadUrl("javascript:(function() {"
                            + "var parent = document.getElementsByTagName('head').item(0);"
                            + "var style = document.createElement('style');"
                            + "style.type = 'text/css';"
                            + "style.innerHTML = window.atob('"
                            + nightCode + "');"
                            + "parent.appendChild(style)"
                            + "})();");
                }

                if (newProgress < 100) {
                    isLoading = true;
                    webView.getProgressBar().setVisibility(View.VISIBLE);
                    webView.getProgressBar().setProgress(newProgress);
                    webView.setRefreshing(true);
                    buttonRefresh.setVisibility(View.GONE);
                    buttonStop.setVisibility(View.VISIBLE);
                } else {
                    isLoading = false;
                    webView.getProgressBar().setVisibility(View.GONE);
                    webView.setRefreshing(false);
                    buttonStop.setVisibility(View.GONE);
                    buttonRefresh.setVisibility(View.VISIBLE);
                    //==========写入恢复页==========
                    if (!isRecovery) {//若不是正在恢复的情况,才记录恢复页
                        editorR = recoveryConfigure.edit();
                        editorR.clear();
                        editorR.putInt("RecoveryNum", webViews.size());
                        int i = 0;
                        for (EnhanceWebView anEnhanceWebView : webViews) {
                            String recoveryPage = "RecoveryPage" + i;
                            i++;
                            editorR.putString(recoveryPage, anEnhanceWebView.getWebView().getUrl());
                        }
                        editorR.apply();
                    }
                    //==========写入恢复页==========
                }
                setCtrlWebBtn();
            }

            //==========全屏播放视频相关==========
            @Override
            public void onShowCustomView(View view, CustomViewCallback callback) {
                layoutFullVideo.setVisibility(View.VISIBLE);
                layoutFullVideo.addView(view);
                hideState();
                mCallback = callback;
                super.onShowCustomView(view, callback);
            }

            @Override
            public void onHideCustomView() {
                if (mCallback != null) {
                    mCallback.onCustomViewHidden();
                }
                layoutFullVideo.removeAllViews();
                layoutFullVideo.setVisibility(View.GONE);
                if (!full) {
                    showState();
                }
                super.onHideCustomView();
            }
            //==========全屏播放视频相关==========

            //==========文件上传相关==========
            @Override
            public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, FileChooserParams fileChooserParams) {
                //处理文件上传
                uploadMessageAboveL = filePathCallback;

                Intent i = new Intent(Intent.ACTION_GET_CONTENT);
                i.addCategory(Intent.CATEGORY_OPENABLE);
                i.setType("*/*");
                startActivityForResult(Intent.createChooser(i, "选择文件"), FILE_CHOOSER_RESULT_CODE);
                return true;
            }
            //==========文件上传相关==========

            //==========HTML5定位==========
            //需要先加入权限
            //<uses-permission android:name="android.permission.INTERNET"/>
            //<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
            //<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
            @Override
            public void onReceivedIcon(WebView view, Bitmap icon) {
                super.onReceivedIcon(view, icon);
            }

            @Override
            public void onGeolocationPermissionsHidePrompt() {
                super.onGeolocationPermissionsHidePrompt();
            }

            @Override
            public void onGeolocationPermissionsShowPrompt(final String origin, final GeolocationPermissions.Callback callback) {
                checkPermissions(new String[]{
                        Manifest.permission.ACCESS_COARSE_LOCATION,
                        Manifest.permission.ACCESS_FINE_LOCATION});//检查权限
                callback.invoke(origin, geo, false);//注意个函数，第二个参数就是是否同意定位权限，第三个是是否希望内核记住
                super.onGeolocationPermissionsShowPrompt(origin, callback);
            }
            //==========HTML5定位==========
        });

        webView.getWebView().loadUrl(url);
    }

    @Override
    protected void onStart() {
        //==========读取配置文件==========
        configure = getSharedPreferences("BijouConfigure", MODE_PRIVATE);//读取配置文件
        engine = configure.getString("Engine", "http://www.baidu.com/s?wd=");
        topContent = configure.getString("TopContent", "title");
        isPaste = configure.getBoolean("Paste", false);
        dropDown = configure.getBoolean("Dropdown", false);
        slideHori = configure.getBoolean("SlideHori", false);
        slideVert = configure.getBoolean("SlideVert", false);
        volKey = configure.getBoolean("VolKey", false);
        geo = configure.getBoolean("Geo", true);
        intercept = configure.getBoolean("Intercept", true);
        javascript = configure.getBoolean("JavaScript", true);
        recovery = configure.getBoolean("Recovery", false);
        //==========读取配置文件==========

        if (isPaste) {//重置粘贴标志
            paste = true;
        }

        for (EnhanceWebView webView : webViews) {
            webView.getWebView().getSettings().setJavaScriptEnabled(javascript);
            webView.setEnabled(dropDown);
            webView.dropDown = dropDown;
        }

        setTopHint();

        super.onStart();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {//设置返回键为返回网页
            if (layoutFind.getVisibility() == View.VISIBLE) {//若查找框打开,则关闭查找框
                layoutFind.setVisibility(View.GONE);
                editSearch.setText("");
                return true;
            } else {
                if (suggestListView.getVisibility() == View.VISIBLE) {
                    if (webViews.get(frontPage).getWebView().getUrl().equals("about:blank")) {
                        openHome();
                    } else {
                        openPage();
                    }
                    return true;
                } else {
                    if (editWebsite.hasFocus()) {
                        editWebsite.clearFocus();
                        return true;
                    } else {
                        if (isLoading) {//若正在加载,则停止加载
                            webViews.get(frontPage).getWebView().stopLoading();
                            return true;
                        } else {
                            if (layoutFullVideo.getVisibility() == View.VISIBLE) {//若正在全屏播放视频,则WebView不做操作
                                return true;
                            } else {
                                if (webViews.get(frontPage).getWebView().canGoBack()) {//若可以后退,则后退
                                    goBack();
                                    return true;
                                } else { //其他情况则退出软件
                                    long secondTime = System.currentTimeMillis();
                                    if (secondTime - firstTime > 2000) {
                                        showTipDialog(2, "重复操作将退出BIJOU", 900);
                                        firstTime = secondTime;
                                        return true;
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }

        if (keyCode == KeyEvent.KEYCODE_VOLUME_UP) {
            if (volKey) {
                webViews.get(frontPage).getWebView().pageUp(false);//音量增加键控制翻页,参数为是否翻到顶部
                return true;
            } else {
                return false;//关闭音量键翻页
            }
        }

        if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN) {
            if (volKey) {
                webViews.get(frontPage).getWebView().pageDown(false);//音量减小键控制翻页,参数为是否翻到底部
                return true;
            } else {
                return false;//关闭音量键翻页
            }
        }

        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onDestroy() {
        //==========获取配置文件==========
        clearCache = configure.getBoolean("ClearCache", true);
        clearFormData = configure.getBoolean("ClearFormdata", false);
        clearHistory = configure.getBoolean("ClearHistory", false);
        clearStorage = configure.getBoolean("ClearStorage", true);
        clearCookies = configure.getBoolean("ClearCookies", false);
        //==========获取配置文件==========

        //==========退出时清除数据处理==========
        for (EnhanceWebView anEnhanceWebView : webViews) {
            if (clearCache && !clearStorage) {
                anEnhanceWebView.getWebView().clearCache(false);//清除缓存,如果为false,则仅清理内存缓存,如果为true,则将会清除本地缓存.
            }
            if (clearFormData) {
                anEnhanceWebView.getWebView().clearFormData();//清除表单数据
            }
            if (clearHistory) {
                anEnhanceWebView.getWebView().clearHistory();//清除历史记录
                //=====清空数据库=====
                List<History> historyList = historyDao.getAllDate();
                try {
                    for (History history : historyList) {
                        historyDao.deleteHistory(history);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            if (clearStorage) {
                anEnhanceWebView.getWebView().clearCache(true);//清除缓存,如果为false,则仅清理内存缓存,如果为true,则将会清除本地缓存.
            }
            anEnhanceWebView.getWebView().clearSslPreferences();//清除当前进程中错误的证书
        }
        if (clearCookies) {
            cookieManager.removeAllCookies(null);
            cookieManager.flush();
        }

        //==========退出时清除数据处理==========

        if (webViews != null) {//退出处理
            for (EnhanceWebView anEnhanceWebView : webViews) {
                destroyWebView(anEnhanceWebView);
            }
            webViews = null;
        }
        super.onDestroy();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        //==========文件上传相关==========
        if (requestCode == FILE_CHOOSER_RESULT_CODE) {
            if (null == uploadMessage && null == uploadMessageAboveL) return;
            Uri result = data == null || resultCode != RESULT_OK ? null : data.getData();
            if (uploadMessageAboveL != null) {
                onActivityResultAboveL(requestCode, resultCode, data);
            } else if (uploadMessage != null) {
                uploadMessage.onReceiveValue(result);
                uploadMessage = null;
            }
        }
        //==========文件上传相关==========

        //==========清除数据==========
        if (requestCode == SETTING && resultCode == SETTING) {
            boolean clearCache = data.getBooleanExtra("ClearCache", true);
            boolean clearFormdata = data.getBooleanExtra("ClearFormdata", false);
            boolean clearHistory = data.getBooleanExtra("ClearHistory", false);
            boolean clearStorage = data.getBooleanExtra("ClearStorage", true);
            boolean clearCookies = data.getBooleanExtra("ClearCookies", false);

            for (EnhanceWebView anEnhanceWebView : webViews) {
                if (clearCache && !clearStorage) {
                    anEnhanceWebView.getWebView().clearCache(false);//清除缓存,如果为false,则仅清理内存缓存,如果为true,则将会清除本地缓存.
                }
                if (clearFormdata) {
                    anEnhanceWebView.getWebView().clearFormData();//清除表单数据
                }
                if (clearHistory) {
                    anEnhanceWebView.getWebView().clearHistory();//清除历史记录
                    //=====清空数据库=====
                    List<History> historyList = historyDao.getAllDate();
                    try {
                        for (History history : historyList) {
                            historyDao.deleteHistory(history);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                if (clearStorage) {
                    anEnhanceWebView.getWebView().clearCache(true);//清除缓存,如果为false,则仅清理内存缓存,如果为true,则将会清除本地缓存.
                }
            }
            if (clearCookies) {
                cookieManager.removeAllCookies(null);
                cookieManager.flush();
            }
        }
        //==========清除数据==========

//        if (requestCode == SETTING && resultCode == UPDATE) {
//            addNewPage("https://www.coolapk.com/apk/top.myhdg.bijou");
//        }

        if (requestCode == SETTING && resultCode == QQ) {
            addNewPage("http://wpa.qq.com/msgrd?v=3&uin=1316740440&site=qq&menu=yes");
        }

        //==========书签相关==========
        if (requestCode == BOOKMARK && resultCode == BOOKMARK) {
            addNewPage(seniorUrl(data.getStringExtra("Bookmark")));
        }
        //==========书签相关==========

        //==========历史记录相关==========
        if (requestCode == HISTORY && resultCode == HISTORY) {
            addNewPage(seniorUrl(data.getStringExtra("History")));
        }
        //==========历史记录相关==========

        //==========二维码扫描相关==========
        if (requestCode == QR && resultCode == RESULT_OK) {
            final String qrContent = data.getStringExtra("result");
            new QRContentDialog(MainActivity.this, R.style.dialogTheme, qrContent, new QRContentDialog.QRListener() {
                @Override
                public void getOperation(int operation) {
                    switch (operation) {
                        case 1:
                            webViews.get(frontPage).getWebView().loadUrl(seniorUrl(qrContent));
                            break;
                        case 2:
                            addNewPage(seniorUrl(qrContent));
                            break;
                        case 3:
                            addNewPageBackstage(seniorUrl(qrContent));
                            break;
                        case 4:
                            Intent intent = new Intent(MainActivity.this, CaptureActivity.class);
                            startActivityForResult(intent, QR);
                            break;
                    }
                }
            }).show();
        }
        //==========二维码扫描相关==========

        super.onActivityResult(requestCode, resultCode, data);
    }

    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    private void onActivityResultAboveL(int requestCode, int resultCode, Intent intent) {
        //==========上传文件相关==========
        if (requestCode != FILE_CHOOSER_RESULT_CODE || uploadMessageAboveL == null)
            return;
        Uri[] results = null;
        if (resultCode == Activity.RESULT_OK) {
            if (intent != null) {
                String dataString = intent.getDataString();
                ClipData clipData = intent.getClipData();
                if (clipData != null) {
                    results = new Uri[clipData.getItemCount()];
                    for (int i = 0; i < clipData.getItemCount(); i++) {
                        ClipData.Item item = clipData.getItemAt(i);
                        results[i] = item.getUri();
                    }
                }
                if (dataString != null)
                    results = new Uri[]{Uri.parse(dataString)};
            }
        }

        uploadMessageAboveL.onReceiveValue(results);

        uploadMessageAboveL = null;
        //==========上传文件相关==========
    }

    private String seniorUrl(String string) {//地址内容转换
        try {
            if (string.length() > 0) {
                if (string.equals("about:blank")) {
                    return string;
                }
                try {
                    URL url = new URL(string);
                    return url.toString();
                } catch (Exception ew) {
                    try {
                        if (Patterns.WEB_URL.matcher("http://" + string).matches()) {
                            return "http://" + string;
                        } else {
                            return engine + string;
                        }
                    } catch (Exception eh) {
                        return engine + string;
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    private void setTopHint() {//设置地址栏显示
        try {
            switch (topContent) {
                case "title":
                    editWebsite.setHint(webViews.get(frontPage).getWebView().getTitle());
                    break;
                case "website":
                    editWebsite.setHint(webViews.get(frontPage).getWebView().getUrl());
                    break;
                default:
                    editWebsite.setHint(webViews.get(frontPage).getWebView().getOriginalUrl().split("/")[2]);
            }
            if (webViews.get(frontPage).getWebView().getUrl().equals("about:blank")) {
                editWebsite.setHint("这里是BIJOU主页");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void initImageListPopupIfNeed() {
        if (longClickImgPopup == null) {

            String[] listItems = new String[]{
                    "查看图片",
                    "保存图片"
            };
            List<String> data = new ArrayList<>();

            Collections.addAll(data, listItems);

            ArrayAdapter adapter = new ArrayAdapter<>(this, R.layout.simple_list_item, data);

            longClickImgPopup = new QMUIListPopup(this, QMUIPopup.DIRECTION_BOTTOM, adapter);
            longClickImgPopup.create(dp2px(this, 100), dp2px(this, 100), new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                    if (i == 0) {
                        Intent intent = new Intent(MainActivity.this, ShowImgActivity.class);
                        intent.putExtra("imgUrl", longClickUrl);
                        startActivity(intent);
                    } else if (i == 1) {
                        new SaveImage().execute(); // Android 4.0以后要使用线程来访问网络
                    }
                    longClickImgPopup.dismiss();
                }
            });
        }
    }

    private void initAnchorListPopupIfNeed() {
        if (longClickAncPopup == null) {

            String[] listItems = new String[]{
                    "复制链接",
                    "后台打开",
                    "新加页打开"
            };
            List<String> data = new ArrayList<>();

            Collections.addAll(data, listItems);

            ArrayAdapter adapter = new ArrayAdapter<>(this, R.layout.simple_list_item, data);

            longClickAncPopup = new QMUIListPopup(this, QMUIPopup.DIRECTION_BOTTOM, adapter);
            longClickAncPopup.create(dp2px(this, 110), dp2px(this, 150), new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                    switch (i) {
                        case 0:
                            clipboardManager.setPrimaryClip(ClipData.newPlainText("text", longClickUrl));
                            showTipDialog(0, "链接已复制", 900);
                            break;
                        case 1:
                            addNewPageBackstage(longClickUrl);
                            showTipDialog(0, "已后台打开链接", 900);
                            break;
                        case 2:
                            addNewPage(longClickUrl);
                            break;
                    }
                    longClickAncPopup.dismiss();
                }
            });
        }
    }

    private void openSuggestList() {
        layoutTopBar.setVisibility(View.VISIBLE);
        suggestListView.setVisibility(View.VISIBLE);
        layoutHome.setVisibility(View.GONE);
        layoutPage.setVisibility(View.GONE);
        editWebsite.requestFocus();
    }

    private void openHome() {
        layoutHome.setVisibility(View.VISIBLE);
        suggestListView.setVisibility(View.GONE);
        layoutPage.setVisibility(View.GONE);
        editWebsite.setText("");
        editWebsite.clearFocus();
        setTopHint();
        layoutFind.setVisibility(View.GONE);
        editSearch.setText("");
        editSearch.clearFocus();
        MyHdgUtils.closeKeyboard(MainActivity.this, editWebsite);
        if (full) {
            fullScreen();
        }
    }

    private void openPage() {
        layoutPage.setVisibility(View.VISIBLE);
        suggestListView.setVisibility(View.GONE);
        layoutHome.setVisibility(View.GONE);
        editWebsite.clearFocus();
        MyHdgUtils.closeKeyboard(MainActivity.this, editWebsite);
        if (full) {
            fullScreen();
        }
    }

    private void goBack() {
        if (isLoading) {
            webViews.get(frontPage).getWebView().stopLoading();
        } else if (webViews.get(frontPage).getWebView().canGoBack()) {
            webViews.get(frontPage).getWebView().goBack();
        }
    }

    private void goForward() {
        if (webViews.get(frontPage).getWebView().canGoForward()) {
            webViews.get(frontPage).getWebView().goForward();
        }
    }

    private void showTipDialog(int mode, String text, int time) {
        final QMUITipDialog tipDialog;
        switch (mode) {
            case 0://成功提示
                tipDialog = new QMUITipDialog.Builder(MainActivity.this)
                        .setIconType(QMUITipDialog.Builder.ICON_TYPE_SUCCESS)
                        .setTipWord(text)
                        .create();
                break;
            case 1://失败提示
                tipDialog = new QMUITipDialog.Builder(MainActivity.this)
                        .setIconType(QMUITipDialog.Builder.ICON_TYPE_FAIL)
                        .setTipWord(text)
                        .create();
                break;
            default://自定义提示
                tipDialog = new QMUITipDialog.Builder(MainActivity.this)
                        .setTipWord(text)
                        .create();
                break;
        }
        tipDialog.show();
        webViews.get(frontPage).postDelayed(new Runnable() {
            @Override
            public void run() {
                tipDialog.dismiss();
            }
        }, time);
    }

    private void getOneText() {
        new RxVolley.Builder()
                .url("https://api.lwl12.com/hitokoto/v1?encode=realjson")
                .shouldCache(false)
                .callback(new HttpCallback() {
                    @Override
                    public void onSuccess(String t) {
                        try {
                            JSONObject jsonObject = new JSONObject(t);
                            oneText.setText(jsonObject.getString("text"));
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                })
                .doTask();
    }

    private void getSuggestList(final String s) {
        //获取关键字提示列表
        new RxVolley.Builder()
                .url("http://sg1.api.bing.com/qsonhs.aspx?type=cb&cb=callback&q=" + s)
                .shouldCache(false)
                .httpMethod(RxVolley.Method.GET)
                .callback(new HttpCallback() {
                    @Override
                    public void onSuccess(String t) {
                        try {
                            suggestList.clear();
                            String string = t.substring(43);
                            JSONObject jsonObjectAll = new JSONObject(string);
                            JSONObject jsonObjectAS = jsonObjectAll.getJSONObject("AS");
                            JSONArray jsonArrayResults = jsonObjectAS.getJSONArray("Results");
                            JSONObject jsonObject = jsonArrayResults.getJSONObject(0);
                            JSONArray jsonArraySuggests = jsonObject.getJSONArray("Suggests");
                            for (int i = 0; i < jsonArraySuggests.length(); i++) {
                                JSONObject jsonObjectTemp = new JSONObject(jsonArraySuggests.get(i).toString());
                                suggestList.add(jsonObjectTemp.get("Txt").toString());
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        adapter.notifyDataSetChanged();
                    }
                })
                .encoding("UTF-8")
                .doTask();
    }

    private void setCtrlWebBtn() {
        //设置前进后退键是否可用
        if (webViews.get(frontPage).getWebView().canGoBack()) {
            buttonBackOff.setEnabled(true);
        } else {
            buttonBackOff.setEnabled(false);
        }
        if (webViews.get(frontPage).getWebView().canGoForward()) {
            buttonForward.setEnabled(true);
        } else {
            buttonForward.setEnabled(false);
        }
    }

    private boolean isLand() {//判断是否横屏
        return this.getResources().getConfiguration().orientation != Configuration.ORIENTATION_PORTRAIT;
    }

    private void fullScreen() {
        layoutTopBar.setVisibility(View.GONE);
        layoutBottomBar.setVisibility(View.GONE);
        buttonExitFull.setVisibility(View.VISIBLE);
        if (isLand()) {
            LinearLayout topBottomLayout = findViewById(R.id.topBottomLayout);
            topBottomLayout.setVisibility(View.GONE);
        }
        hideState();
    }

    private void exitFullScreen() {
        layoutTopBar.setVisibility(View.VISIBLE);
        layoutBottomBar.setVisibility(View.VISIBLE);
        buttonExitFull.setVisibility(View.GONE);
        showState();

        if (isLand()) {
            LinearLayout topBottomLayout = findViewById(R.id.topBottomLayout);
            topBottomLayout.setVisibility(View.VISIBLE);
            hideState();
        }
    }

    private void hideState() {//隐藏状态栏
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
    }

    private void showState() {//显示状态栏
        getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
    }

    private void addNewPage(String url) {//添加新页
        if (webViews.size() != 0) {
            webViews.get(frontPage).setVisibility(View.GONE);//隐藏之前显示页面
        }
        frontPage = webViews.size();//更改显示页

        EnhanceWebView webView = new EnhanceWebView(MainActivity.this);
        initWebView(webView, url);//初始化WebView
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.MATCH_PARENT);
        webView.setLayoutParams(params);//设置布局
        webView.setVisibility(View.VISIBLE);

        webViews.add(webView);
        layoutWebView.addView(webView);
        setTopHint();
        if (frontPage == 9) {
            showTipDialog(2, "新增过多页面可能会引起系统卡顿,或者其他未知问题,请谨慎添加", 1500);
        }

        openHome();
    }

    private void addNewPageBackstage(String url) {//后台添加新页
        EnhanceWebView webView = new EnhanceWebView(MainActivity.this);
        initWebView(webView, url);//初始化WebView
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.MATCH_PARENT);
        webView.setLayoutParams(params);//设置布局
        webView.setVisibility(View.GONE);

        webViews.add(webView);
        layoutWebView.addView(webView);

        showTipDialog(0, "已后台打开链接", 900);
    }

    private void destroyWebView(EnhanceWebView webViewD) {//销毁WebView
        ((ViewGroup) webViewD.getParent()).removeView(webViewD);
        WebView webView = webViewD.getWebView();
        webView.loadUrl("about:blank");
        webView.stopLoading();
        webView.setWebChromeClient(null);
        webView.setWebViewClient(null);
        webView.destroy();
    }

    private String getClearAdDivJs() {
        //生成屏蔽广告JS
        StringBuilder js = new StringBuilder("javascript:");
        Resources res = MainActivity.this.getResources();
        String[] adDivsId = res.getStringArray(R.array.adDivsId);
        for (int i = 0; i < adDivsId.length; i++) {
            js.append("var adDiv").append(i).append("= document.getElementById('").
                    append(adDivsId[i]).append("');if(adDiv").append(i).
                    append(" != null)adDiv").append(i).append(".parentNode.removeChild(adDiv").
                    append(i).append(");");
        }
        return js.toString();
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);

        changeLayout();
    }

    //横竖屏切换处理
    private void changeLayout() {
        //切换横竖屏时，关闭底部菜单，防止布局切换出错
        moreDialog.dismiss();
        toolDialog.dismiss();
        multiDialog.dismiss();

        setContentView(R.layout.activity_main);//横竖屏切换时，更改布局

        findViews();
        setListeners();

        //重新添加WebView进入布局
        for (EnhanceWebView anEnhanceWebView : webViews) {
            ViewGroup parent = (ViewGroup) anEnhanceWebView.getParent();
            if (parent != null) {
                parent.removeAllViews();//移除原layout中WebView
            }
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                    ViewGroup.LayoutParams.MATCH_PARENT);
            anEnhanceWebView.setLayoutParams(params);//设置布局
            anEnhanceWebView.setVisibility(View.GONE);
            layoutWebView.addView(anEnhanceWebView);
            setTopHint();
        }
        webViews.get(frontPage).setVisibility(View.VISIBLE);

        //=====关闭全屏视频=====
        if (mCallback != null) {
            mCallback.onCustomViewHidden();
        }
        layoutFullVideo.removeAllViews();
        layoutFullVideo.setVisibility(View.GONE);
        //=====关闭全屏视频=====

        if (isLand()) {//横屏时隐藏状态栏
            hideState();
        } else {
            if (!full) {
                exitFullScreen();
            }
        }

        //开关一次，防止空数据
        multiDialog.show();
        multiDialog.dismiss();
        //开关一次，加快下次启动速度
        moreDialog.show();
        moreDialog.dismiss();
        toolDialog.show();
        toolDialog.dismiss();

        if (!webViews.get(frontPage).getWebView().getUrl().equals("about:blank")) {
            openPage();
        }
    }

    // ==========检查和申请权限==========
    final int PERMISSION_REQ_CODE = 110;

    public void checkPermissions(final String[] permissions) {
        // 检查本应用是否有权限
        for (String permission : permissions) {
            if (ContextCompat.checkSelfPermission(this, permission)
                    != PackageManager.PERMISSION_GRANTED) {
                // 系统将弹出一个对话框，询问用户是否授权
                ActivityCompat.requestPermissions(this, permissions, PERMISSION_REQ_CODE);
            }
        }
    }

    // 权限申请的结果
    // requestCode：请求码
    // permissions：申请的N个权限
    // grantResults：每个权限是否被授权
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String permissions[], @NonNull int[] grantResults) {
        if (requestCode == PERMISSION_REQ_CODE) {
            for (int i = 0; i < permissions.length; i++) {
                if (grantResults[i] != PackageManager.PERMISSION_GRANTED) {
                    showTipDialog(1, permissions[i] + "未授权!", 900);
                }
            }
        }
    }
// ==========检查和申请权限==========

    //==========JS通讯接口==========
    @SuppressWarnings("InfiniteRecursion")
    private class JavascriptInterface {
        JavascriptInterface() {

        }

        @android.webkit.JavascriptInterface
        public void showSource(String html) {
            //获取html源码
            MainActivity.html = html;
        }
    }
//==========JS通讯接口==========

    //==========利用线程保存图片==========
    @SuppressLint("StaticFieldLeak")
    private class SaveImage extends AsyncTask<String, Void, String> {
        @Override
        protected String doInBackground(String... params) {
            String result;
            checkPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE});//检查权限
            try {
                //=====创建文件=====
                int idx = longClickUrl.lastIndexOf(".");
                String ext = longClickUrl.substring(idx);
                final String image = new Date().getTime() + ext + ".jpg";
                final File file = getExternalFilesDir(image);
                assert file != null;
                if (file.exists()) {
                    r1 = file.delete();
                } else {
                    r1 = file.mkdir();
                }
                //=====创建文件=====
                InputStream inputStream = null;
                URL url = new URL(longClickUrl);
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                conn.setRequestMethod("GET");
                conn.setConnectTimeout(20000);
                if (conn.getResponseCode() == 200) {
                    inputStream = conn.getInputStream();
                }
                byte[] buffer = new byte[4096];
                int len;
                FileOutputStream outStream = new FileOutputStream(file);
                assert inputStream != null;
                while ((len = inputStream.read(buffer)) != -1) {
                    outStream.write(buffer, 0, len);
                }
                //=====保存到系统图库=====
                MediaStore.Images.Media.insertImage(MainActivity.this.getContentResolver(),
                        file.getAbsolutePath(), image, null);// 把文件插入到系统图库
                MainActivity.this.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + file.getAbsolutePath())));// 通知图库更新
                r1 = file.delete();//删除原文件
                outStream.flush();
                outStream.close();
                result = "若无异常,图片将在片刻后保存至系统图库";
                //=====保存到系统图库=====
            } catch (Exception e) {
                result = "保存失败" + e.getLocalizedMessage();
            }
            return result;
        }

        @Override
        protected void onPostExecute(String result) {
            showTipDialog(2, result, 1500);
        }
    }
//==========利用线程保存图片==========

    static class TagUtils {
        //==========全屏播放视频相关==========
        private static String getTagByUrl(String url) {
            if (url.contains("qq")) {
                return "tvp_fullscreen_button"; // http://m.v.qq.com
            } else if (url.contains("youku")) {
                return "x-zoomin";              // http://www.youku.com
            } else if (url.contains("bilibili")) {
                return "icon-widescreen";       // http://www.bilibili.com/mobile/index.html
            } else if (url.contains("acfun")) {
                return "controller-btn-fullscreen"; //http://m.acfun.tv   无效
            } else if (url.contains("le")) {
                return "hv_ico_screen";         // http://m.le.com  无效
            }
            return "";
        }

        //  "javascript:document.getElementsByClassName('" + referParser(url) + "')[frontPage].addEventListener('click',function(){local_obj.playing();return false;});"
        static String getJs(String url) {
            String tag = getTagByUrl(url);
            if (TextUtils.isEmpty(tag)) {
                return "javascript:";
            } else {
                return "javascript:document.getElementsByClassName('" + tag + "')[frontPage].addEventListener('click',function(){onClick.fullVedio();return false;});";
            }
        }
        //==========全屏播放视频相关==========
    }

    static class QRContentDialog extends Dialog {
        private String content;

        private QRListener qrListener;

        QRContentDialog(@NonNull Context context, int themeResId, String content, QRListener qrListener) {
            super(context, themeResId);
            this.content = content;
            this.qrListener = qrListener;
        }

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);

            //==========设置更改UADialog位置及动画==========
            Window window = getWindow();
            assert window != null;
            window.setGravity(Gravity.CENTER); // 设置dialog显示位置
            window.setWindowAnimations(R.style.dialogTheme); // 添加动画效果
            setContentView(R.layout.dialog_qr);
            setCanceledOnTouchOutside(false);// 点击Dialog外部消失
            //==========设置更改UADialog位置及动画==========

            EditText qrContent = findViewById(R.id.qrContent);
            qrContent.setText(content);

            Button openCurrent = findViewById(R.id.openCurrent);
            openCurrent.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    qrListener.getOperation(1);
                    QRContentDialog.this.dismiss();
                }
            });

            Button openNew = findViewById(R.id.openNew);
            openNew.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    qrListener.getOperation(2);
                    QRContentDialog.this.dismiss();
                }
            });

            Button openBack = findViewById(R.id.openBack);
            openBack.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    qrListener.getOperation(3);
                    QRContentDialog.this.dismiss();
                }
            });

            Button scanAgain = findViewById(R.id.scanAgain);
            scanAgain.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    qrListener.getOperation(4);
                    QRContentDialog.this.dismiss();
                }
            });

            Button closeContent = findViewById(R.id.closeContent);
            closeContent.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    QRContentDialog.this.dismiss();
                }
            });
        }

        public interface QRListener {
            void getOperation(int operation);
        }
    }

    class MoreDialog extends Dialog {
        private Context context;

        MoreDialog(@NonNull Context context, int themeResId) {
            super(context, themeResId);
            this.context = context;
        }

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);

            //==========设置更改UADialog位置及动画==========
            Window window = getWindow();
            assert window != null;
            window.setGravity(Gravity.BOTTOM); // 设置dialog显示位置
            window.setWindowAnimations(R.style.slide_animation); // 添加动画效果
            setContentView(R.layout.dialog_more);
            DisplayMetrics displayMetrics = new DisplayMetrics();
            ((Activity) context).getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
            WindowManager.LayoutParams layoutParams = getWindow().getAttributes();
            layoutParams.width = displayMetrics.widthPixels; // 设置dialog宽度
            getWindow().setAttributes(layoutParams);
            setCanceledOnTouchOutside(true);// 点击Dialog外部消失
            //==========设置更改UADialog位置及动画==========

            LinearLayout buttonBookmark = findViewById(R.id.buttonBookmark);
            buttonBookmark.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    MoreDialog.this.dismiss();

                    Intent intent = new Intent(MainActivity.this, BookmarkActivity.class);
                    intent.putExtra("Title", webViews.get(frontPage).getWebView().getTitle());
                    intent.putExtra("Website", webViews.get(frontPage).getWebView().getUrl());
                    MainActivity.this.startActivityForResult(intent, BOOKMARK);
                }
            });

            LinearLayout buttonHistory = findViewById(R.id.buttonHistory);
            buttonHistory.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    MoreDialog.this.dismiss();

                    Intent intent = new Intent(MainActivity.this, HistoryActivity.class);
                    MainActivity.this.startActivityForResult(intent, HISTORY);
                }
            });

            LinearLayout buttonDownload = findViewById(R.id.buttonDownload);
            buttonDownload.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    MoreDialog.this.dismiss();

                    Intent intent = new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS);
                    MainActivity.this.startActivity(intent);
                }
            });

            LinearLayout buttonShare = findViewById(R.id.buttonShare);
            buttonShare.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    MoreDialog.this.dismiss();

                    Intent intent = new Intent(Intent.ACTION_SEND);
                    intent.setType("text/plain");
                    String shareTitle = webViews.get(frontPage).getWebView().getTitle() + "\n";
                    String shareUrl = webViews.get(frontPage).getWebView().getUrl();
                    if (shareUrl.equals("about:blank")) {
                        shareTitle = "基于Android原生WebView开发的轻量级浏览器！";
                        shareUrl = "https://www.coolapk.com/apk/top.myhdg.bijou";
                    }
                    intent.putExtra(Intent.EXTRA_TEXT, "来自BIJOU的分享：" + shareTitle + shareUrl);
                    MainActivity.this.startActivity(intent);
                }
            });

            LinearLayout buttonUA = findViewById(R.id.buttonUA);
            buttonUA.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    MoreDialog.this.dismiss();

                    final UADialog uaDialog = new UADialog(MainActivity.this, R.style.dialogTheme, new UADialog.CustomUa() {
                        @Override
                        public void getCustomUa(String ua) {
                            customUA = ua;
                        }
                    }, webViews.get(frontPage).getWebView().getSettings().getUserAgentString());
                    uaDialog.show();

                    uaDialog.setUaAndroidClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            uaDialog.dismiss();
                            for (EnhanceWebView anEnhanceWebView : webViews) {
                                anEnhanceWebView.getWebView().getSettings()
                                        .setUserAgentString("(Linux; Android 7.1.1; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/63.0.3239.111 Mobile Safari/537.36");
                                anEnhanceWebView.getWebView().reload();
                            }
                        }
                    });

                    uaDialog.setUaEdgeClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            uaDialog.dismiss();
                            for (EnhanceWebView anEnhanceWebView : webViews) {
                                anEnhanceWebView.getWebView().getSettings()
                                        .setUserAgentString("(Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36 Edge/16.16299");
                                anEnhanceWebView.getWebView().reload();
                            }
                        }
                    });

                    uaDialog.setUaChromeClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            uaDialog.dismiss();
                            for (EnhanceWebView anEnhanceWebView : webViews) {
                                anEnhanceWebView.getWebView().getSettings()
                                        .setUserAgentString("(Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3298.4 Safari/537.36");
                                anEnhanceWebView.getWebView().reload();
                            }
                        }
                    });

                    uaDialog.setUaIEClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            uaDialog.dismiss();
                            for (EnhanceWebView anEnhanceWebView : webViews) {
                                anEnhanceWebView.getWebView().getSettings()
                                        .setUserAgentString("(Windows NT 10.0; WOW64; Trident/7.0; rv:11.0) like Gecko");
                                anEnhanceWebView.getWebView().reload();
                            }
                        }
                    });

                    uaDialog.setUaIOSClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            uaDialog.dismiss();
                            for (EnhanceWebView anEnhanceWebView : webViews) {
                                anEnhanceWebView.getWebView().getSettings()
                                        .setUserAgentString("(iPhone; CPU iPhone OS 11_2_1 like Mac OS X) AppleWebKit/604.4.7 (KHTML, like Gecko) Version/11.0 Mobile/15C153 Safari/604.1");
                                anEnhanceWebView.getWebView().reload();
                            }
                        }
                    });

                    uaDialog.setUaCustomClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            uaDialog.dismiss();
                            if (!customUA.equals("")) {
                                for (EnhanceWebView anEnhanceWebView : webViews) {
                                    anEnhanceWebView.getWebView().getSettings().setUserAgentString(customUA);
                                    anEnhanceWebView.getWebView().reload();
                                }
                            }
                            MyHdgUtils.toggleKeyboard(MainActivity.this, uaDialog.editUA);
                        }
                    });
                }
            });

            LinearLayout buttonTool = findViewById(R.id.buttonTool);
            buttonTool.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    MoreDialog.this.dismiss();

                    toolDialog.show();
                }
            });

            LinearLayout buttonSetting = findViewById(R.id.buttonSetting);
            buttonSetting.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    MoreDialog.this.dismiss();

                    Intent intent = new Intent(MainActivity.this, SettingsActivity.class);
                    MainActivity.this.startActivityForResult(intent, SETTING);
                }
            });

            LinearLayout buttonExit = findViewById(R.id.buttonExit);
            buttonExit.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    MoreDialog.this.dismiss();

                    onDestroy();
                    System.exit(0);
                }
            });

            Button buttonDismissMore = findViewById(R.id.buttonDismissMore);
            buttonDismissMore.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    MoreDialog.this.dismiss();
                }
            });
        }
    }

    class ToolDialog extends Dialog {
        private Context context;

        ToolDialog(@NonNull Context context, int themeResId) {
            super(context, themeResId);
            this.context = context;
        }

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);

            //==========设置更改UADialog位置及动画==========
            Window window = getWindow();
            assert window != null;
            window.setGravity(Gravity.BOTTOM); // 设置dialog显示位置
            window.setWindowAnimations(R.style.slide_animation); // 添加动画效果
            setContentView(R.layout.dialog_tool);
            DisplayMetrics displayMetrics = new DisplayMetrics();
            ((Activity) context).getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
            WindowManager.LayoutParams layoutParams = getWindow().getAttributes();
            layoutParams.width = displayMetrics.widthPixels; // 设置dialog宽度
            getWindow().setAttributes(layoutParams);
            setCanceledOnTouchOutside(true);// 点击Dialog外部消失
            //==========设置更改UADialog位置及动画==========

            LinearLayout buttonNoImg = findViewById(R.id.buttonNoImg);
            buttonNoImg.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    ToolDialog.this.dismiss();

                    noImg = !noImg;
                    if (noImg) {
                        showTipDialog(0, "无图模式已开启", 900);
                    } else {
                        showTipDialog(0, "无图模式已关闭", 900);
                    }
                    editorM = noImgConfigure.edit();
                    editorM.putBoolean("NoImg", noImg);
                    editorM.apply();
                    for (EnhanceWebView anEnhanceWebView : webViews) {
                        anEnhanceWebView.getWebView().getSettings().setLoadsImagesAutomatically(!noImg);
                        anEnhanceWebView.getWebView().reload();
                    }

                }
            });

            LinearLayout buttonFull = findViewById(R.id.buttonFull);
            buttonFull.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    ToolDialog.this.dismiss();

                    full = !full;
                    editorF = fullConfigure.edit();
                    editorF.putBoolean("Full", full);
                    editorF.apply();
                    if (full) {
                        showTipDialog(0, "全屏模式已开启", 900);
                        fullScreen();
                    } else {
                        showTipDialog(0, "全屏模式已关闭", 900);
                        exitFullScreen();
                    }
                }
            });

            LinearLayout buttonNight = findViewById(R.id.buttonNight);
            buttonNight.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    ToolDialog.this.dismiss();

                    if (SharedPreferencesMgr.getInt("Theme", 0) == 1) {
                        showTipDialog(0, "夜间模式已关闭", 900);
                        SharedPreferencesMgr.setInt("Theme", 0);
                        setTheme(R.style.DayTheme);
                    } else {
                        showTipDialog(0, "夜间模式已开启", 900);
                        SharedPreferencesMgr.setInt("Theme", 1);
                        setTheme(R.style.NightTheme);
                    }
                    final View rootView = getWindow().getDecorView();
                    ColorUiUtil.changeTheme(rootView, getTheme());
                    for (EnhanceWebView webView : webViews) {
                        webView.getWebView().reload();
                    }
                    //翻转屏幕,防止布局出错
                    if (isLand()) {
                        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
                        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
                        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_USER);
                    } else {
                        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
                        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
                        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_USER);
                    }
                }
            });

            LinearLayout buttonSource = findViewById(R.id.buttonSource);
            buttonSource.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    ToolDialog.this.dismiss();

                    if (webViews.get(frontPage).getWebView().getUrl().startsWith("http://")) {
                        Intent intent = new Intent(MainActivity.this, SourceActivity.class);
                        intent.putExtra("Html", html);
                        startActivity(intent);
                    } else {
                        showTipDialog(1, "目前仅支持http页面查看源码", 1500);
                    }
                }
            });

            LinearLayout buttonExportImg = findViewById(R.id.buttonExportImg);
            buttonExportImg.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    ToolDialog.this.dismiss();

                    if (layoutHome.getVisibility() == View.VISIBLE) {
                        showTipDialog(1, "不支持主页导出", 900);
                    } else {
                        checkPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE});//检查权限

                        showTipDialog(2, "若无异常,图片将在片刻后导入系统图库", 1500);

                        final EnhanceWebView webView = webViews.get(frontPage);
                        //=====创建文件=====
                        final String title = webView.getWebView().getTitle() + ".jpg";
                        final File file = getExternalFilesDir(title);
                        assert file != null;
                        if (file.exists()) {
                            r1 = file.delete();
                        } else {
                            r1 = file.mkdir();
                        }
                        //=====创建文件=====

                        //新开一个线程处理耗时任务
                        new Thread(new Runnable() {
                            @Override
                            public void run() {
                                FileOutputStream fos;
                                try {
                                    fos = new FileOutputStream(file.getAbsoluteFile());
                                    Bitmap bitmap = Bitmap.createBitmap(webView.getPageWidth(), webView.getPageHeight(), Bitmap.Config.ARGB_8888);
                                    Canvas canvas = new Canvas(bitmap);
                                    webView.draw(canvas);
                                    bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
                                    if (!bitmap.isRecycled()) {
                                        bitmap.recycle();
                                        //bitmap = null;
                                        System.gc();
                                    }
                                    //=====保存到系统图库=====
                                    MediaStore.Images.Media.insertImage(MainActivity.this.getContentResolver(),
                                            file.getAbsolutePath(), title, null);// 把文件插入到系统图库
                                    MainActivity.this.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + file.getAbsolutePath())));// 通知图库更新
                                    r1 = file.delete();//删除原文件
                                    fos.flush();
                                    fos.close();
                                    //=====保存到系统图库=====
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                            }
                        }).start();
                    }
                }
            });

            LinearLayout buttonExportPdf = findViewById(R.id.buttonExportPdf);
            buttonExportPdf.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    ToolDialog.this.dismiss();

                    if (layoutHome.getVisibility() == View.VISIBLE) {
                        showTipDialog(1, "不支持主页导出", 900);
                    } else {
                        showTipDialog(2, "导出的PDF保存在\"下载\"目录中", 1500);

                        PrintManager printManager = (PrintManager) getSystemService(Context.PRINT_SERVICE);
                        String jobName = getString(R.string.app_name) + " Document";
                        PrintDocumentAdapter printAdapter = webViews.get(frontPage).getWebView().createPrintDocumentAdapter(jobName);
                        assert printManager != null;
                        printManager.print(jobName, printAdapter, new PrintAttributes.Builder().build());
                    }

                }
            });

            Button buttonDismissTool = findViewById(R.id.buttonDismissTool);
            buttonDismissTool.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    ToolDialog.this.dismiss();
                }
            });
        }
    }
}
